import React, { useEffect, useState } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Grid,
  Button,
  Alert,
  CircularProgress,
  Chip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  Divider,
  Paper,
  LinearProgress
} from '@mui/material';
import {
  Refresh,
  CleaningServices,
  Assessment,
  Warning,
  CheckCircle,
  Schedule,
  Error
} from '@mui/icons-material';
import { useContentFeatureAdmin } from '../../hooks/useRecommendation';
import { TaskStatus } from '../../types/recommendation/recommendation';
import { getTaskStatusText } from '../../utils/recommendation';
import styles from './RecommendationAdmin.module.css';

const RecommendationAdmin: React.FC = () => {
  const {
    loading,
    error,
    statistics,
    fetchStatistics,
    retryFailedTasks,
    cleanupTimeoutTasks,
    clearError
  } = useContentFeatureAdmin();

  const [cleanupDialogOpen, setCleanupDialogOpen] = useState(false);
  const [timeoutMinutes, setTimeoutMinutes] = useState<number>(30);
  const [operationSuccess, setOperationSuccess] = useState<string | null>(null);

  // 页面加载时获取统计信息
  useEffect(() => {
    fetchStatistics();
  }, [fetchStatistics]);

  // 处理重试失败任务
  const handleRetryFailed = async () => {
    const result = await retryFailedTasks();
    if (result) {
      setOperationSuccess(`成功重置了 ${result.retryCount} 个失败任务为待处理状态`);
      setTimeout(() => setOperationSuccess(null), 5000);
    }
  };

  // 处理清理超时任务
  const handleCleanupTimeout = async () => {
    const result = await cleanupTimeoutTasks({ timeoutMinutes });
    if (result) {
      setOperationSuccess(`成功清理了 ${result.retryCount} 个超时任务（超时时间: ${timeoutMinutes}分钟）`);
      setCleanupDialogOpen(false);
      setTimeout(() => setOperationSuccess(null), 5000);
    }
  };

  // 获取任务状态对应的颜色和图标
  const getStatusConfig = (status: TaskStatus) => {
    switch (status) {
      case TaskStatus.PENDING:
        return { color: 'warning', icon: <Schedule /> };
      case TaskStatus.PROCESSING:
        return { color: 'info', icon: <CircularProgress size={16} /> };
      case TaskStatus.COMPLETED:
        return { color: 'success', icon: <CheckCircle /> };
      case TaskStatus.FAILED:
        return { color: 'error', icon: <Error /> };
      default:
        return { color: 'default', icon: <Warning /> };
    }
  };

  // 计算总任务数
  const getTotalTasks = () => {
    if (!statistics?.taskStatusStatistics) return 0;
    return Object.values(statistics.taskStatusStatistics).reduce((sum, count) => sum + count, 0);
  };

  // 计算完成率
  const getCompletionRate = () => {
    if (!statistics?.taskStatusStatistics) return 0;
    const total = getTotalTasks();
    const completed = statistics.taskStatusStatistics[TaskStatus.COMPLETED] || 0;
    return total > 0 ? Math.round((completed / total) * 100) : 0;
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Typography variant="h4" className={styles.title}>
          推荐系统管理
        </Typography>
        <Typography variant="body1" className={styles.subtitle}>
          内容特征生成任务管理和系统监控
        </Typography>
      </div>

      {/* 操作成功提示 */}
      {operationSuccess && (
        <Alert severity="success" sx={{ mb: 3 }} onClose={() => setOperationSuccess(null)}>
          {operationSuccess}
        </Alert>
      )}

      {/* 错误提示 */}
      {error && (
        <Alert severity="error" sx={{ mb: 3 }} onClose={clearError}>
          {error}
        </Alert>
      )}

      {/* 加载状态 */}
      {loading && !statistics && (
        <Box display="flex" justifyContent="center" alignItems="center" minHeight="200px">
          <CircularProgress />
          <Typography variant="body1" sx={{ ml: 2 }}>
            正在加载统计信息...
          </Typography>
        </Box>
      )}

      {/* 统计信息 */}
      {statistics && (
        <>
          {/* 概览卡片 */}
          <Grid container spacing={3} sx={{ mb: 3 }}>
            <Grid size={{ xs: 12, md: 3 }}>
              <Card className={styles.overviewCard}>
                <CardContent>
                  <Box display="flex" alignItems="center" justifyContent="space-between">
                    <Box>
                      <Typography color="textSecondary" gutterBottom>
                        总任务数
                      </Typography>
                      <Typography variant="h4" component="div">
                        {getTotalTasks()}
                      </Typography>
                    </Box>
                    <Assessment color="primary" sx={{ fontSize: 40 }} />
                  </Box>
                </CardContent>
              </Card>
            </Grid>

            <Grid size={{ xs: 12, md: 3 }}>
              <Card className={styles.overviewCard}>
                <CardContent>
                  <Box display="flex" alignItems="center" justifyContent="space-between">
                    <Box>
                      <Typography color="textSecondary" gutterBottom>
                        失败任务
                      </Typography>
                      <Typography variant="h4" component="div" color="error">
                        {statistics.failedTaskCount}
                      </Typography>
                    </Box>
                    <Error color="error" sx={{ fontSize: 40 }} />
                  </Box>
                </CardContent>
              </Card>
            </Grid>

            <Grid size={{ xs: 12, md: 3 }}>
              <Card className={styles.overviewCard}>
                <CardContent>
                  <Box display="flex" alignItems="center" justifyContent="space-between">
                    <Box>
                      <Typography color="textSecondary" gutterBottom>
                        完成率
                      </Typography>
                      <Typography variant="h4" component="div" color="success.main">
                        {getCompletionRate()}%
                      </Typography>
                    </Box>
                    <CheckCircle color="success" sx={{ fontSize: 40 }} />
                  </Box>
                  <LinearProgress
                    variant="determinate"
                    value={getCompletionRate()}
                    sx={{ mt: 1 }}
                  />
                </CardContent>
              </Card>
            </Grid>

            <Grid size={{ xs: 12, md: 3 }}>
              <Card className={styles.overviewCard}>
                <CardContent>
                  <Box display="flex" alignItems="center" justifyContent="space-between">
                    <Box>
                      <Typography color="textSecondary" gutterBottom>
                        处理中
                      </Typography>
                      <Typography variant="h4" component="div" color="info.main">
                        {statistics.taskStatusStatistics[TaskStatus.PROCESSING] || 0}
                      </Typography>
                    </Box>
                    <CircularProgress size={40} />
                  </Box>
                </CardContent>
              </Card>
            </Grid>
          </Grid>

          {/* 详细统计 */}
          <Grid container spacing={3}>
            {/* 任务状态统计 */}
            <Grid size={{ xs: 12, md: 6 }}>
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    任务状态统计
                  </Typography>
                  <Divider sx={{ mb: 2 }} />
                  
                  {Object.entries(statistics.taskStatusStatistics).map(([status, count]) => {
                    const statusConfig = getStatusConfig(status as TaskStatus);
                    return (
                      <Box
                        key={status}
                        display="flex"
                        alignItems="center"
                        justifyContent="space-between"
                        py={1}
                      >
                        <Box display="flex" alignItems="center">
                          {statusConfig.icon}
                          <Typography variant="body1" sx={{ ml: 1 }}>
                            {getTaskStatusText(status as TaskStatus)}
                          </Typography>
                        </Box>
                        <Chip
                          label={count}
                          color={statusConfig.color as any}
                          size="small"
                        />
                      </Box>
                    );
                  })}
                </CardContent>
              </Card>
            </Grid>

            {/* 系统配置 */}
            <Grid size={{ xs: 12, md: 6 }}>
              <Card>
                <CardContent>
                  <Typography variant="h6" gutterBottom>
                    系统配置
                  </Typography>
                  <Divider sx={{ mb: 2 }} />
                  
                  <Grid container spacing={2}>
                    <Grid size={{ xs: 6 }}>
                      <Paper elevation={1} sx={{ p: 2, textAlign: 'center' }}>
                        <Typography color="textSecondary" variant="body2">
                          批处理大小
                        </Typography>
                        <Typography variant="h6">
                          {statistics.systemConfig.batchSize}
                        </Typography>
                      </Paper>
                    </Grid>
                    <Grid size={{ xs: 6 }}>
                      <Paper elevation={1} sx={{ p: 2, textAlign: 'center' }}>
                        <Typography color="textSecondary" variant="body2">
                          最大并发数
                        </Typography>
                        <Typography variant="h6">
                          {statistics.systemConfig.maxConcurrent}
                        </Typography>
                      </Paper>
                    </Grid>
                    <Grid size={{ xs: 6 }}>
                      <Paper elevation={1} sx={{ p: 2, textAlign: 'center' }}>
                        <Typography color="textSecondary" variant="body2">
                          重试间隔(ms)
                        </Typography>
                        <Typography variant="h6">
                          {statistics.systemConfig.waitRetryInterval}
                        </Typography>
                      </Paper>
                    </Grid>
                    <Grid size={{ xs: 6 }}>
                      <Paper elevation={1} sx={{ p: 2, textAlign: 'center' }}>
                        <Typography color="textSecondary" variant="body2">
                          最大尝试次数
                        </Typography>
                        <Typography variant="h6">
                          {statistics.systemConfig.maxNoLockAttempts}
                        </Typography>
                      </Paper>
                    </Grid>
                  </Grid>
                </CardContent>
              </Card>
            </Grid>
          </Grid>

          {/* 操作按钮 */}
          <Box display="flex" gap={2} justifyContent="center" mt={4}>
            <Button
              variant="outlined"
              startIcon={<Refresh />}
              onClick={fetchStatistics}
              disabled={loading}
            >
              刷新统计
            </Button>
            
            <Button
              variant="contained"
              color="warning"
              startIcon={<Refresh />}
              onClick={handleRetryFailed}
              disabled={loading || statistics.failedTaskCount === 0}
            >
              重试失败任务 ({statistics.failedTaskCount})
            </Button>
            
            <Button
              variant="contained"
              color="error"
              startIcon={<CleaningServices />}
              onClick={() => setCleanupDialogOpen(true)}
              disabled={loading}
            >
              清理超时任务
            </Button>
          </Box>
        </>
      )}

      {/* 清理超时任务对话框 */}
      <Dialog open={cleanupDialogOpen} onClose={() => setCleanupDialogOpen(false)}>
        <DialogTitle>清理超时任务</DialogTitle>
        <DialogContent>
          <Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
            清理长时间停留在"处理中"状态的超时任务，将它们重置为"待处理"状态。
          </Typography>
          <TextField
            autoFocus
            margin="dense"
            label="超时时间（分钟）"
            type="number"
            fullWidth
            variant="outlined"
            value={timeoutMinutes}
            onChange={(e) => setTimeoutMinutes(Number(e.target.value))}
            helperText="超过此时间的PROCESSING任务将被重置"
            inputProps={{ min: 1, max: 1440 }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setCleanupDialogOpen(false)}>
            取消
          </Button>
          <Button
            onClick={handleCleanupTimeout}
            variant="contained"
            color="error"
            disabled={loading || timeoutMinutes < 1}
          >
            确认清理
          </Button>
        </DialogActions>
      </Dialog>
    </div>
  );
};

export default RecommendationAdmin; 